<?php
namespace backend\models;

use Yii;
use yii\base\Model;
use yii\base\Exception;
use common\models\product;

class ProductForm extends Model
{
	public $name;
	public $id;
	public $price;
	public $pro_img;

	private $_product;

	public function __construct($id=null, $config = [])
	{
		if (!empty($id)) {
			$product = Product::findOne($id);
			$this->name = $product->name;
			$this->price = $product->price;
			$this->id = $product->id;
			$this->pro_img = $product->image;
		} else {
			$product = new Product;
		}
		$this->_product = $product;

		return parent::__construct($config);
	}

	public function formName()
    {
        return '';
    }

	public function rules()
	{
		return [
			[['name', 'price'], 'required'],
			['name', 'string'],
			['price', 'double'],
			['pro_img', 'file']
		];
	}

	public function addOrUpdate()
	{
		$product = $this->_product;
		$product->name = $this->name;
		$product->price = $this->price;
		$product->status = Product::ACTIVE_STATUS;
		if ($this->pro_img) {
		 	$base_name = uniqid();
            $extension = $this->pro_img->extension;
            $this->fileExists(Yii::$app->params['upload']);
            $this->pro_img->saveAs(Yii::$app->params['upload'] . $base_name . '.' . $extension);
            $product->image = $base_name . '.' . $extension;
		}
		if ($product->save(false)) {

			return true;
		} else {

			return false;
		}
	}

    public function fileExists($uploadpath)
    {
        if(!file_exists($uploadpath)){
            mkdir($uploadpath);
        }
        return $uploadpath;
    }

    public function attributeLabels()
    {
    	return [
    		'pro_img' => '',
    	];
    }

}	